package com.kongchengji.zhanguafou.service;

import com.alibaba.fastjson.JSONObject;
import com.kongchengji.zhanguafou.constant.WxInfo;
import com.kongchengji.zhanguafou.domain.AccessTokenDO;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Order(1)
public class AccessTokenService implements CommandLineRunner {
    @Autowired
    CreateMenuService createMenuService;
    @Override
    public void run(String... args) {
        try {
            Thread thread = new Thread(() -> {
                //间隔一段时间就去获取accessToken
                while (true) {
                    WxInfo.accessToken = getAccessToken(WxInfo.APPID, WxInfo.APPSECRIPT);
                    try {
                        if (WxInfo.accessToken != null) {
                            //获取到access_token 休眠7000秒,大约2个小时左右
                            Thread.sleep(7000 * 1000);
                        } else {
                            //获取失败
                            Thread.sleep(1000 * 3); //获取的access_token为空 休眠3秒
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        System.out.println("发生异常：" + e.getMessage());
                        e.printStackTrace();
                        try {
                            Thread.sleep(1000 * 10); //发生异常休眠1秒
                        } catch (Exception e1) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            thread.start();
            //等待获取AccessToken
            Thread.sleep(3000);
            createMenuService.createMenu();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private AccessTokenDO getAccessToken(String appId, String appSecret) {
        Request request = new Request.Builder()
                .url("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret)
                .build();
        OkHttpClient client = new OkHttpClient();
        try {
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            JSONObject reply = JSONObject.parseObject(body);
            AccessTokenDO accessToken = new AccessTokenDO();
            accessToken.setToken((String) reply.get("access_token"));
            accessToken.setExpireSecond((Integer) reply.get("expires_in"));
            return accessToken;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
